<?php
namespace App\Admin\Controllers\Basics;

use App\Importer\Basics\BImporter;
use App\Models\Basics\Currency;
use App\Models\Basics\ExchangeRate;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Illuminate\Support\Facades\DB;
class ERUploadController extends AdminController{

    protected $title = '汇率上传';

    protected function grid()
    {
        return view("basics.exchange-rate.index");
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $re = $this->_importFile($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importFile(UploadedFile $file){
        try{
            $data = Excel::toArray(new BImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            foreach($data as $row){
                $count++;
                $_currencyCode = $row[0] ? trim($row[0]) : '';
                $_effective = $row[1] ? RExcel::toDateTime(trim($row[1])) : '';
                $rateOdds = $row[2] ? trim($row[2]) : '';
                if(!$_currencyCode || !$_effective || !$rateOdds){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                $currencyCode = strtoupper($_currencyCode);
                $key = $currencyCode.'_'.$_effective;
                if(!in_array($key,$arr)){
                    $arr[$count] = $key;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                $currencyExist = Currency::existByCode($currencyCode);
                if(!$currencyExist){
                    $errors[$count] = $_currencyCode.'系统不存在';
                    continue;
                }
                if(!strtotime($_effective)){
                    $errors[$count] = '日期格式有误';
                    continue;
                }
                DB::beginTransaction();
                ExchangeRate::query()->updateOrCreate([
                    'currency_code' => $currencyCode,
                    'effective_at' => date('Y-m-01',strtotime($_effective))
                ],['rate_odds' => $rateOdds]);
                DB::commit();
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }
}
